/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.vdg.lockapp;

import java.util.ArrayList;
import java.util.List;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.ads.AdSize;
import com.handmark.pulltorefresh.library.IndexableListView;
import com.vdg.adapter.ListAppAdapter;
import com.vdg.data.AppInformation;
import com.vdg.lockapp.listener.OnLoadAppInforListener;
import com.vdg.lockapp.service.LockService;
import com.vdg.lockapp.service.LockService.LocalBinder;
import com.vdg.util.Utilities;

public class FragmentListApplications extends Fragment {
	private ArrayList<AppInformation> mListtAppInfor = new ArrayList<AppInformation>();
	private IndexableListView mListApp;
	private ListAppAdapter mListAppAdapter;
	private static final String TAG = "ListAppPickerActivity";
	private ArrayList<String> mListSelected;
	public final static String LIST_SELECTED_KEY = "list_selected";
	private LockService mService;
	private FrameLayout mFrmPrg;
	private Handler mHandler = new Handler();
	View v;
	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@TargetApi(Build.VERSION_CODES.HONEYCOMB)
		// required for Sherlock's invalidateOptionsMenu */
		public void onServiceConnected(ComponentName name, IBinder service) {
			LocalBinder binder = (LocalBinder) service;
			Log.v(TAG, "service connected");
			mService = binder.getService();
			init();
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// TODO Auto-generated method stub

		}
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		v = inflater.inflate(R.layout.list_app_layout, container, false);
		mListSelected = new ArrayList<String>();
		Intent serviceIntent = new Intent(getActivity(), LockService.class);
		getActivity().bindService(serviceIntent, mServiceConnection,
				Activity.BIND_AUTO_CREATE);
		return v;
		// get a list of installed apps.
	}

	private void init() {
		mFrmPrg = (FrameLayout) v.findViewById(R.id.fr_prg);
		mListApp = (IndexableListView) v.findViewById(R.id.lv_app);
		mFrmPrg.setVisibility(View.VISIBLE);
		mService.queryAppData(new OnLoadAppInforListener() {

			@Override
			public void onLoadSucessFully(
					ArrayList<AppInformation> listAppInformation,
					ArrayList<String> listAppLocked) {

				// TODO Auto-generated method stub
				mFrmPrg.setVisibility(View.GONE);
				mListSelected.clear();
				mListSelected.addAll(listAppLocked);
				mListtAppInfor.clear();
				mListtAppInfor.addAll(listAppInformation);
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						Log.v(TAG, "activity =" + getActivity()
								+ "listappinfor = " + mListtAppInfor);
						mListAppAdapter = new ListAppAdapter(getActivity(), 0,
								mListtAppInfor);
						mListApp.setAdapter(mListAppAdapter);
						mListAppAdapter.notifyDataSetChanged();
						mListApp.setOnItemClickListener(new OnItemClickListener() {
							@Override
							public void onItemClick(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								mListtAppInfor.get(arg2).setIsSelected(
										!mListtAppInfor.get(arg2)
												.isIsSelected());
								String name = mListtAppInfor.get(arg2).packageName;
								if (mListSelected.contains(name)) {
									mListSelected.remove(name);
									mService.removeLockApp(name);
								} else {
									mListSelected.add(name);
									mService.addLockApp(name);
								}
								updateListAppSharedPreferences();
								arg0.getAdapter().getView(arg2, arg1, mListApp);
							}
						});
					}
				});
			}
		});
	}

	public void updateListAppSharedPreferences() {
		Log.v(TAG, "save list " + mListSelected);
		Utilities.saveListAppLocked(getActivity(), mListSelected);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Log.v(TAG, "ondestroy");
		mService.unRegisOnLoaddAppInforListener();
		getActivity().unbindService(mServiceConnection);
		super.onDestroy();

	}
}
